////package org.example.serve;
////
////import com.fasterxml.jackson.databind.ObjectMapper;
////import lombok.extern.slf4j.Slf4j;
////import org.example.beans.LidarPoint;
////import org.springframework.stereotype.Component;
////
////import javax.annotation.PostConstruct;
////import java.io.IOException;
////import java.net.DatagramPacket;
////import java.net.DatagramSocket;
////import java.util.ArrayList;
////import java.util.Collections;
////import java.util.List;
////
////@Slf4j
////@Component
////public class UdpLidarServer {
////
////    private static final int UDP_PORT = 8082;
////    // 定义数据量的最大值，可根据实际需求调整
////    private static final int MAX_POINT_COUNT = 200000;
////    private final List<LidarPoint> pointCloud = Collections.synchronizedList(new ArrayList<>());
////    private final ObjectMapper objectMapper = new ObjectMapper();
////
////    @PostConstruct
////    public void startServer() {
////        new Thread(() -> {
////            try (DatagramSocket socket = new DatagramSocket(UDP_PORT)) {
////                log.info("UDP LiDAR Server started on port {}", UDP_PORT);
////                byte[] buffer = new byte[65507]; // UDP最大包长度
////
////                while (true) {
////                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
////                    socket.receive(packet);
////                    processPacket(packet);
////                }
////            } catch (IOException e) {
////                log.error("UDP Server error", e);
////            }
////        }).start();
////    }
////
////    private void processPacket(DatagramPacket packet) {
////        try {
////            String jsonStr = new String(packet.getData(), 0, packet.getLength());
////            LidarPoint[] points = objectMapper.readValue(jsonStr, LidarPoint[].class);
////
////            synchronized (pointCloud) {
////                Collections.addAll(pointCloud, points);
////                log.debug("Added {} points. Total: {}", points.length, pointCloud.size());
////
////                // 检查数据量是否超出最大值
////                while (pointCloud.size() > MAX_POINT_COUNT) {
////                    pointCloud.remove(0); // 删除最早的数据
////                }
////            }
////        } catch (Exception e) {
////            log.error("Failed to parse point cloud data", e);
////        }
////    }
////
////    public List<LidarPoint> getPointCloud() {
////        return new ArrayList<>(pointCloud);
////    }
////
////    public void clearPoints() {
////        pointCloud.clear();
////    }
////
////    // 添加获取最大数据量的方法
////    public int getMaxPointCount() {
////        return MAX_POINT_COUNT;
////    }
////}
//
//package org.example.serve;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.example.beans.LidarPoint;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.io.File;
//import java.io.IOException;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.List;
//import java.util.Timer;
//import java.util.TimerTask;
//
//@Slf4j
//@Component
//public class UdpLidarServer {
//
//    private static final int UDP_PORT = 8082;
//    private static final int MAX_POINT_COUNT = 700000;
//    private final List<LidarPoint> pointCloud = Collections.synchronizedList(new ArrayList<>());
//    private final ObjectMapper objectMapper = new ObjectMapper();
//    private static final String SAVE_FILE = "data_folder/received_data.json"; // 保存数据的文件路径
//    private Timer timer;
//
//    @PostConstruct
//    public void startServer() {
//        new Thread(() -> {
//            try (DatagramSocket socket = new DatagramSocket(UDP_PORT)) {
//                log.info("UDP LiDAR Server started on port {}", UDP_PORT);
//                byte[] buffer = new byte[65507];
//
//                while (true) {
//                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//                    socket.receive(packet);
//                    processPacket(packet);
//                }
//            } catch (IOException e) {
//                log.error("UDP Server error", e);
//            }
//        }).start();
//
//        // 启动定时任务，每 30 秒保存一次数据
//        startSaveTask();
//    }
//
//    private void processPacket(DatagramPacket packet) {
//        try {
//            String jsonStr = new String(packet.getData(), 0, packet.getLength());
//            LidarPoint[] points = objectMapper.readValue(jsonStr, LidarPoint[].class);
//
//            synchronized (pointCloud) {
//                Collections.addAll(pointCloud, points);
//                log.debug("Added {} points. Total: {}", points.length, pointCloud.size());
//
//                while (pointCloud.size() > MAX_POINT_COUNT) {
//                    pointCloud.remove(0);
//                }
//            }
//        } catch (Exception e) {
//            log.error("Failed to parse point cloud data", e);
//        }
//    }
//
//    public List<LidarPoint> getPointCloud() {
//        return new ArrayList<>(pointCloud);
//    }
//
//    public void clearPoints() {
//        pointCloud.clear();
//    }
//
//    public int getMaxPointCount() {
//        return MAX_POINT_COUNT;
//    }
//
//    private void startSaveTask() {
//        timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                saveDataToFile();
//            }
//        }, 0, 30 * 1000); // 每 30 秒执行一次
//    }
//
//    private void saveDataToFile() {
//        synchronized (pointCloud) {
//            File file = new File(SAVE_FILE);
//            File parent = file.getParentFile();
//            if (parent != null &&!parent.exists()) {
//                parent.mkdirs();
//            }
//
//            try {
//                objectMapper.writeValue(file, pointCloud);
//                log.info("Saved data to file: {}", file.getAbsolutePath());
//            } catch (IOException e) {
//                log.error("Failed to save data to file", e);
//            }
//        }
//    }
//
//    // 关闭定时任务的方法（如果需要在某些情况下停止定时保存）
//    public void stopSaveTask() {
//        if (timer != null) {
//            timer.cancel();
//            timer.purge();
//        }
//    }
//}


//
//
//package org.example.serve;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.example.beans.LidarPoint;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.io.File;
//import java.io.IOException;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.List;
//import java.util.Timer;
//import java.util.TimerTask;
//
//@Slf4j
//@Component
//public class UdpLidarServer {
//
//    private static final int UDP_PORT = 8082;
//    private static final int MAX_POINT_COUNT = 100000;
//    private final List<LidarPoint> pointCloud = Collections.synchronizedList(new ArrayList<>());
//    private final ObjectMapper objectMapper = new ObjectMapper();
//    private static final String SAVE_FILE = "data_folder/received_data.json";
//    private Timer timer;
//
//    @PostConstruct
//    public void startServer() {
//        new Thread(() -> {
//            try (DatagramSocket socket = new DatagramSocket(UDP_PORT)) {
//                log.info("UDP LiDAR Server started on port {}", UDP_PORT);
//
//                while (true) {
//                    // 接收数据
//                    String jsonData = receiveJsonData(socket);
//                    if (jsonData != null) {
//
//                        processJsonData(jsonData);
//                    }
//                }
//            } catch (IOException e) {
//                log.error("UDP Server error", e);
//            }
//        }).start();
//
//        // 启动定时任务，每 30 秒保存一次数据
//        startSaveTask();
//    }
//
//    private String receiveJsonData(DatagramSocket socket) throws IOException {
//        byte[] buffer = new byte[65507];
//        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//        socket.receive(packet);
//        return new String(packet.getData(), 0, packet.getLength());
//    }
//
//    private void processJsonData(String jsonData) {
//        try {
//            // 简单验证 JSON 格式，这里假设接收到的是数组类型的 JSON
//            if (jsonData.startsWith("[") && jsonData.endsWith("]")) {
//                LidarPoint[] points = objectMapper.readValue(jsonData, LidarPoint[].class);
//
//                synchronized (pointCloud) {
//                    Collections.addAll(pointCloud, points);
//                    log.debug("Added {} points. Total: {}", points.length, pointCloud.size());
//
//                    while (pointCloud.size() > MAX_POINT_COUNT) {
//                        pointCloud.remove(0);
//                    }
//                }
//            } else {
//                log.warn("Received data is not in valid JSON array format: {}", jsonData);
//            }
//        } catch (Exception e) {
//            log.error("Failed to parse point cloud data. Raw data: {}. Error: {}", jsonData, e);
//        }
//    }
//
//    public List<LidarPoint> getPointCloud() {
//        return new ArrayList<>(pointCloud);
//    }
//
//    public void clearPoints() {
//        pointCloud.clear();
//    }
//
//    public int getMaxPointCount() {
//        return MAX_POINT_COUNT;
//    }
//
//    private void startSaveTask() {
//        timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                saveDataToFile();
//            }
//        }, 0, 30 * 1000);
//    }
//
//    private void saveDataToFile() {
//        synchronized (pointCloud) {
//            File file = new File(SAVE_FILE);
//            File parent = file.getParentFile();
//            if (parent != null &&!parent.exists()) {
//                parent.mkdirs();
//            }
//
//            try {
//                objectMapper.writeValue(file, pointCloud);
//                log.info("Saved data to file: {}", file.getAbsolutePath());
//            } catch (IOException e) {
//                log.error("Failed to save data to file", e);
//            }
//        }
//    }
//
//    public void stopSaveTask() {
//        if (timer != null) {
//            timer.cancel();
//            timer.purge();
//        }
//    }
////}


//package org.example.serve;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.example.beans.LidarPoint;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.io.File;
//import java.io.IOException;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.List;
//import java.util.Timer;
//import java.util.TimerTask;
//
//@Slf4j
//@Component
//public class UdpLidarServer {
//
//    private static final int UDP_PORT = 8082;
//    private static final int MAX_POINT_COUNT = 100000;
//    private final List<LidarPoint> pointCloud = Collections.synchronizedList(new ArrayList<>());
//    private final ObjectMapper objectMapper = new ObjectMapper();
//    private static final String SAVE_FILE = "data_folder/received_data.json";
//    private Timer dataPrintTimer; // 新增用于打印数据的定时器
//    private Timer saveTimer;
//
//    @PostConstruct
//    public void startServer() {
//        new Thread(() -> {
//            try (DatagramSocket socket = new DatagramSocket(UDP_PORT)) {
//                log.info("UDP LiDAR Server started on port {}", UDP_PORT);
//
//                while (true) {
//                    // 接收数据
//                    String jsonData = receiveJsonData(socket);
//                    if (jsonData != null) {
//                        processJsonData(jsonData);
//                    }
//                }
//            } catch (IOException e) {
//                log.error("UDP Server error", e);
//            }
//        }).start();
//
//        // 启动定时任务，每 30 秒保存一次数据
//        startSaveTask();
//        // 启动定时任务，每 5 秒打印一次数据
//        startPrintTask();
//    }
//
//    private String receiveJsonData(DatagramSocket socket) throws IOException {
//        byte[] buffer = new byte[65507];
//        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//        socket.receive(packet);
//        return new String(packet.getData(), 0, packet.getLength());
//    }
//
//    private void processJsonData(String jsonData) {
//        try {
//            // 简单验证 JSON 格式，这里假设接收到的是数组类型的 JSON
//            if (jsonData.startsWith("[") && jsonData.endsWith("]")) {
//                LidarPoint[] points = objectMapper.readValue(jsonData, LidarPoint[].class);
//
//                synchronized (pointCloud) {
//                    Collections.addAll(pointCloud, points);
//                    log.debug("Added {} points. Total: {}", points.length, pointCloud.size());
//
//                    while (pointCloud.size() > MAX_POINT_COUNT) {
//                        pointCloud.remove(0);
//                    }
//                }
//            } else {
//                log.warn("Received data is not in valid JSON array format: {}", jsonData);
//            }
//        } catch (Exception e) {
//            log.error("Failed to parse point cloud data. Raw data: {}. Error: {}", jsonData, e);
//        }
//    }
//
//    public List<LidarPoint> getPointCloud() {
//        return new ArrayList<>(pointCloud);
//    }
//
//    public void clearPoints() {
//        pointCloud.clear();
//    }
//
//    public int getMaxPointCount() {
//        return MAX_POINT_COUNT;
//    }
//
//    private void startSaveTask() {
//        saveTimer = new Timer();
//        saveTimer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                saveDataToFile();
//            }
//        }, 0, 30 * 1000);
//    }
//
//    private void startPrintTask() {
//        dataPrintTimer = new Timer();
//        dataPrintTimer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                synchronized (pointCloud) {
//                    if (!pointCloud.isEmpty()) {
//                        log.info("Printing point cloud data: {}", pointCloud);
//                    }
//                }
//            }
//        }, 0, 5 * 1000);
//    }
//
//    private void saveDataToFile() {
//        synchronized (pointCloud) {
//            File file = new File(SAVE_FILE);
//            File parent = file.getParentFile();
//            if (parent != null &&!parent.exists()) {
//                parent.mkdirs();
//            }
//
//            try {
//                objectMapper.writeValue(file, pointCloud);
//                log.info("Saved data to file: {}", file.getAbsolutePath());
//            } catch (IOException e) {
//                log.error("Failed to save data to file", e);
//            }
//        }
//    }
//
//    public void stopSaveTask() {
//        if (saveTimer != null) {
//            saveTimer.cancel();
//            saveTimer.purge();
//        }
//    }
//
//    public void stopPrintTask() {
//        if (dataPrintTimer != null) {
//            dataPrintTimer.cancel();
//            dataPrintTimer.purge();
//        }
//    }
//}
//
//package org.example.serve;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.example.beans.LidarPoint;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.io.File;
//import java.io.IOException;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.List;
//import java.util.Timer;
//import java.util.TimerTask;
//
//@Slf4j
//@Component
//public class UdpLidarServer {
//
//    private static final int UDP_PORT = 8082;
//    private static final int MAX_POINT_COUNT = 100000;
//    private final List<LidarPoint> pointCloud = Collections.synchronizedList(new ArrayList<>());
//    private final ObjectMapper objectMapper = new ObjectMapper();
//    private static final String SAVE_FILE = "data_folder/received_data.json";
//    private Timer dataPrintTimer;
//    private Timer saveTimer;
//    // 新增缓冲区来存储不完整的数据
//    private StringBuilder buffer = new StringBuilder();
//
//    @PostConstruct
//    public void startServer() {
//        new Thread(() -> {
//            try (DatagramSocket socket = new DatagramSocket(UDP_PORT)) {
//                log.info("UDP LiDAR Server started on port {}", UDP_PORT);
//
//                while (true) {
//                    String jsonData = receiveJsonData(socket);
//                    if (jsonData != null) {
//                        processJsonData(jsonData);
//                    }
//                }
//            } catch (IOException e) {
//                log.error("UDP Server error", e);
//            }
//        }).start();
//
//        startSaveTask();
//        startPrintTask();
//    }
//
//    private String receiveJsonData(DatagramSocket socket) throws IOException {
//        byte[] buffer = new byte[65507];
//        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//        socket.receive(packet);
//        return new String(packet.getData(), 0, packet.getLength());
//    }
//
//    private void processJsonData(String jsonData) {
//        // 将新数据添加到缓冲区
//        buffer.append(jsonData);
//        log.debug("Received data added to buffer: {}", jsonData);
//
//        while (true) {
//            int startIndex = buffer.indexOf("[");
//            int endIndex = buffer.lastIndexOf("]");
//
//            // 检查是否有完整的 JSON 数组
//            if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
//                String validJson = buffer.substring(startIndex, endIndex + 1);
//                try {
//                    LidarPoint[] points = objectMapper.readValue(validJson, LidarPoint[].class);
//                    synchronized (pointCloud) {
//                        Collections.addAll(pointCloud, points);
//                        log.info("Added {} points. Total: {}", points.length, pointCloud.size());
//
//                        while (pointCloud.size() > MAX_POINT_COUNT) {
//                            pointCloud.remove(0);
//                        }
//                    }
//                } catch (Exception e) {
//                    log.error("Failed to parse point cloud data. Raw data: {}. Error: {}", validJson, e);
//                }
//                // 从缓冲区中移除已处理的数据
//                buffer.delete(0, endIndex + 1);
//            } else {
//                log.debug("No complete JSON array found in buffer, waiting for more data.");
//                break;
//            }
//        }
//    }
//
//    public List<LidarPoint> getPointCloud() {
//        return new ArrayList<>(pointCloud);
//    }
//
//    public void clearPoints() {
//        pointCloud.clear();
//    }
//
//    public int getMaxPointCount() {
//        return MAX_POINT_COUNT;
//    }
//
//    private void startSaveTask() {
//        saveTimer = new Timer();
//        saveTimer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                saveDataToFile();
//            }
//        }, 0, 30 * 1000);
//    }
//
//    private void startPrintTask() {
//        dataPrintTimer = new Timer();
//        dataPrintTimer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                synchronized (pointCloud) {
//                    if (!pointCloud.isEmpty()) {
//                        log.info("Printing point cloud data: {}", pointCloud);
//                    }
//                }
//            }
//        }, 0, 5 * 1000);
//    }
//
//    private void saveDataToFile() {
//        synchronized (pointCloud) {
//            File file = new File(SAVE_FILE);
//            File parent = file.getParentFile();
//            if (parent != null &&!parent.exists()) {
//                parent.mkdirs();
//            }
//
//            try {
//                objectMapper.writeValue(file, pointCloud);
//                log.info("Saved data to file: {}", file.getAbsolutePath());
//            } catch (IOException e) {
//                log.error("Failed to save data to file", e);
//            }
//        }
//    }
//
//    public void stopSaveTask() {
//        if (saveTimer != null) {
//            saveTimer.cancel();
//            saveTimer.purge();
//        }
//    }
//
//    public void stopPrintTask() {
//        if (dataPrintTimer != null) {
//            dataPrintTimer.cancel();
//            dataPrintTimer.purge();
//        }
//    }
//}

//
//
//package org.example.serve;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.example.beans.LidarPoint;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.io.File;
//import java.io.IOException;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.List;
//import java.util.Timer;
//import java.util.TimerTask;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//
//@Slf4j
//@Component
//public class UdpLidarServer {
//
//    private static final int UDP_PORT = 8082;
//    private static final int MAX_POINT_COUNT = 100000;
//    private static final int BATCH_SIZE = 10000; // 批量写入的大小
//    private static final int PARSE_BATCH_SIZE = 100; // 解析批量大小
//    private final List<LidarPoint> pointCloud = Collections.synchronizedList(new ArrayList<>());
//    private final ObjectMapper objectMapper = new ObjectMapper();
//    private Timer dataPrintTimer;
//    // 新增缓冲区来存储不完整的数据
//    private StringBuilder buffer = new StringBuilder();
//    private static final String FILE_PATH = "point_cloud_data.json";
//    private final ExecutorService fileWriteExecutor = Executors.newSingleThreadExecutor();
//    private final ExecutorService parseExecutor = Executors.newSingleThreadExecutor();
//    private final List<String> jsonDataBatch = Collections.synchronizedList(new ArrayList<>());
//
//    @PostConstruct
//    public void startServer() {
//        new Thread(() -> {
//            try (DatagramSocket socket = new DatagramSocket(UDP_PORT)) {
//                log.info("UDP LiDAR Server started on port {}", UDP_PORT);
//
//                while (true) {
//                    String jsonData = receiveJsonData(socket);
//                    if (jsonData != null) {
//                        processJsonData(jsonData);
//                    }
//                }
//            } catch (IOException e) {
//                log.error("UDP Server error", e);
//            }
//        }).start();
//
//        startPrintTask();
//    }
//
//    private String receiveJsonData(DatagramSocket socket) throws IOException {
//        byte[] buffer = new byte[65507];
//        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//        socket.receive(packet);
//        return new String(packet.getData(), 0, packet.getLength());
//    }
//
//    private void processJsonData(String jsonData) {
//        // 将新数据添加到缓冲区
//        buffer.append(jsonData);
//        log.debug("Received data added to buffer: {}", jsonData);
//
//        while (true) {
//            int startIndex = buffer.indexOf("[");
//            int endIndex = buffer.lastIndexOf("]");
//
//            // 检查是否有完整的 JSON 数组
//            if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
//                String validJson = buffer.substring(startIndex, endIndex + 1);
//                jsonDataBatch.add(validJson);
//                // 从缓冲区中移除已处理的数据
//                buffer.delete(0, endIndex + 1);
//
//                if (jsonDataBatch.size() >= PARSE_BATCH_SIZE) {
//                    parseExecutor.submit(() -> {
//                        List<String> batchToParse;
//                        synchronized (jsonDataBatch) {
//                            batchToParse = new ArrayList<>(jsonDataBatch);
//                            jsonDataBatch.clear();
//                        }
//                        parseJsonBatch(batchToParse);
//                    });
//                }
//            } else {
//                log.debug("No complete JSON array found in buffer, waiting for more data.");
//                break;
//            }
//        }
//    }
//
//    private void parseJsonBatch(List<String> jsonBatch) {
//        try {
//            StringBuilder combinedJson = new StringBuilder("[");
//            for (int i = 0; i < jsonBatch.size(); i++) {
//                if (i > 0) {
//                    combinedJson.append(",");
//                }
//                combinedJson.append(jsonBatch.get(i).substring(1, jsonBatch.get(i).length() - 1));
//            }
//            combinedJson.append("]");
//
//            LidarPoint[] points = objectMapper.readValue(combinedJson.toString(), LidarPoint[].class);
//            synchronized (pointCloud) {
//                Collections.addAll(pointCloud, points);
//                log.info("Added {} points. Total: {}", points.length, pointCloud.size());
//
//                while (pointCloud.size() > MAX_POINT_COUNT) {
//                    pointCloud.remove(0);
//                }
//
//                if (pointCloud.size() >= BATCH_SIZE) {
//                    savePointCloudToFileAsync();
//                }
//            }
//        } catch (Exception e) {
//            log.error("Failed to parse point cloud data batch. Error: {}", e);
//        }
//    }
//
//    private void savePointCloudToFileAsync() {
//        fileWriteExecutor.submit(() -> {
//            List<LidarPoint> pointsToSave;
//            synchronized (pointCloud) {
//                pointsToSave = new ArrayList<>(pointCloud);
//                pointCloud.clear();
//            }
//            try {
//                objectMapper.writeValue(new File(FILE_PATH), pointsToSave);
//                log.info("Point cloud data saved to file: {}", FILE_PATH);
//            } catch (IOException e) {
//                log.error("Failed to save point cloud data to file: {}", FILE_PATH, e);
//            }
//        });
//    }
//
//    public List<LidarPoint> getPointCloud() {
//        return new ArrayList<>(pointCloud);
//    }
//
//    public void clearPoints() {
//        pointCloud.clear();
//    }
//
//    public int getMaxPointCount() {
//        return MAX_POINT_COUNT;
//    }
//
//    private void startPrintTask() {
//        dataPrintTimer = new Timer();
//        dataPrintTimer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                synchronized (pointCloud) {
//                    if (!pointCloud.isEmpty()) {
//                        log.info("Printing point cloud data: {}", pointCloud);
//                    }
//                }
//            }
//        }, 0, 5 * 1000);
//    }
//}
//


//package org.example.serve;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.example.beans.LidarPoint;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.io.File;
//import java.io.IOException;
//import java.net.DatagramPacket;
//import java.net.DatagramSocket;
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.Date;
//import java.util.List;
//import java.util.Timer;
//import java.util.TimerTask;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//
//@Slf4j
//@Component
//public class UdpLidarServer {
//
//    private static final int UDP_PORT = 8082;
//    private static final int MAX_POINT_COUNT = 100000;
//    private static final int BATCH_SIZE = 10000; // 批量写入的大小
//    private static final int PARSE_BATCH_SIZE = 100; // 解析批量大小
//    private final List<LidarPoint> pointCloud = Collections.synchronizedList(new ArrayList<>());
//    private final ObjectMapper objectMapper = new ObjectMapper();
//    private Timer dataPrintTimer;
//    // 新增缓冲区来存储不完整的数据
//    private StringBuilder buffer = new StringBuilder();
//    private final ExecutorService fileWriteExecutor = Executors.newSingleThreadExecutor();
//    private final ExecutorService parseExecutor = Executors.newSingleThreadExecutor();
//    private final List<String> jsonDataBatch = Collections.synchronizedList(new ArrayList<>());
//    private String folderPath;
//
//    @PostConstruct
//    public void startServer() {
//        // 在程序启动时生成时间戳并创建文件夹
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//        String timestamp = dateFormat.format(new Date());
//        folderPath = "point_cloud_data_" + timestamp;
//        File folder = new File(folderPath);
//        if (!folder.exists()) {
//            folder.mkdirs();
//        }
//
//        new Thread(() -> {
//            try (DatagramSocket socket = new DatagramSocket(UDP_PORT)) {
//                log.info("UDP LiDAR Server started on port {}", UDP_PORT);
//
//                while (true) {
//                    String jsonData = receiveJsonData(socket);
//                    if (jsonData != null) {
//                        processJsonData(jsonData);
//                    }
//                }
//            } catch (IOException e) {
//                log.error("UDP Server error", e);
//            }
//        }).start();
//
//        startPrintTask();
//    }
//
//    private String receiveJsonData(DatagramSocket socket) throws IOException {
//        byte[] buffer = new byte[65507];
//        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//        socket.receive(packet);
//        return new String(packet.getData(), 0, packet.getLength());
//    }
//
//    private void processJsonData(String jsonData) {
//        // 将新数据添加到缓冲区
//        buffer.append(jsonData);
//        log.debug("Received data added to buffer: {}", jsonData);
//
//        while (true) {
//            int startIndex = buffer.indexOf("[");
//            int endIndex = buffer.lastIndexOf("]");
//
//            // 检查是否有完整的 JSON 数组
//            if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
//                String validJson = buffer.substring(startIndex, endIndex + 1);
//                jsonDataBatch.add(validJson);
//                // 从缓冲区中移除已处理的数据
//                buffer.delete(0, endIndex + 1);
//
//                if (jsonDataBatch.size() >= PARSE_BATCH_SIZE) {
//                    parseExecutor.submit(() -> {
//                        List<String> batchToParse;
//                        synchronized (jsonDataBatch) {
//                            batchToParse = new ArrayList<>(jsonDataBatch);
//                            jsonDataBatch.clear();
//                        }
//                        parseJsonBatch(batchToParse);
//                    });
//                }
//            } else {
//                log.debug("No complete JSON array found in buffer, waiting for more data.");
//                break;
//            }
//        }
//    }
//
//    private void parseJsonBatch(List<String> jsonBatch) {
//        try {
//            StringBuilder combinedJson = new StringBuilder("[");
//            for (int i = 0; i < jsonBatch.size(); i++) {
//                if (i > 0) {
//                    combinedJson.append(",");
//                }
//                combinedJson.append(jsonBatch.get(i).substring(1, jsonBatch.get(i).length() - 1));
//            }
//            combinedJson.append("]");
//
//            LidarPoint[] points = objectMapper.readValue(combinedJson.toString(), LidarPoint[].class);
//            synchronized (pointCloud) {
//                Collections.addAll(pointCloud, points);
//                log.info("Added {} points. Total: {}", points.length, pointCloud.size());
//
//                while (pointCloud.size() > MAX_POINT_COUNT) {
//                    pointCloud.remove(0);
//                }
//
//                if (pointCloud.size() >= BATCH_SIZE) {
//                    savePointCloudToFileAsync();
//                }
//            }
//        } catch (Exception e) {
//            log.error("Failed to parse point cloud data batch. Error: {}", e);
//        }
//    }
//
//    private void savePointCloudToFileAsync() {
//        fileWriteExecutor.submit(() -> {
//            List<LidarPoint> pointsToSave;
//            synchronized (pointCloud) {
//                pointsToSave = new ArrayList<>(pointCloud);
//                pointCloud.clear();
//            }
//            try {
//                String filePath = folderPath + "/point_cloud_data.json";
//                objectMapper.writeValue(new File(filePath), pointsToSave);
//                log.info("Point cloud data saved to file: {}", filePath);
//            } catch (IOException e) {
//                log.error("Failed to save point cloud data to file. Error: {}", e);
//            }
//        });
//    }
//
//    public List<LidarPoint> getPointCloud() {
//        return new ArrayList<>(pointCloud);
//    }
//
//    public void clearPoints() {
//        pointCloud.clear();
//    }
//
//    public int getMaxPointCount() {
//        return MAX_POINT_COUNT;
//    }
//
//    private void startPrintTask() {
//        dataPrintTimer = new Timer();
//        dataPrintTimer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                synchronized (pointCloud) {
//                    if (!pointCloud.isEmpty()) {
//                        log.info("Printing point cloud data: {}", pointCloud);
//                    }
//                }
//            }
//        }, 0, 5 * 1000);
//    }
//}
package org.example.serve;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.example.beans.LidarPoint;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@Slf4j
@Component
public class UdpLidarServer {

    private static final int UDP_PORT = 8082;
    private static final int MAX_POINT_COUNT = 100000;
    private final List<LidarPoint> pointCloud = Collections.synchronizedList(new ArrayList<>());
    private final ObjectMapper objectMapper = new ObjectMapper();
    private Timer dataPrintTimer;
    // 新增缓冲区来存储不完整的数据
    private StringBuilder buffer = new StringBuilder();

    @PostConstruct
    public void startServer() {
        new Thread(() -> {
            try (DatagramSocket socket = new DatagramSocket(UDP_PORT)) {
                log.info("UDP LiDAR Server started on port {}", UDP_PORT);

                while (true) {
                    String jsonData = receiveJsonData(socket);
                    if (jsonData != null) {
                        processJsonData(jsonData);
                    }
                }
            } catch (IOException e) {
                log.error("UDP Server error", e);
            }
        }).start();

        startPrintTask();
    }

    private String receiveJsonData(DatagramSocket socket) throws IOException {
        byte[] buffer = new byte[65507];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        socket.receive(packet);
        return new String(packet.getData(), 0, packet.getLength());
    }

    private void processJsonData(String jsonData) {
        // 将新数据添加到缓冲区
        buffer.append(jsonData);
        log.debug("Received data added to buffer: {}", jsonData);

        while (true) {
            int startIndex = buffer.indexOf("[");
            int endIndex = buffer.lastIndexOf("]");

            // 检查是否有完整的 JSON 数组
            if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
                String validJson = buffer.substring(startIndex, endIndex + 1);
                try {
                    LidarPoint[] points = objectMapper.readValue(validJson, LidarPoint[].class);
                    synchronized (pointCloud) {
                        Collections.addAll(pointCloud, points);
                        log.info("Added {} points. Total: {}", points.length, pointCloud.size());

                        while (pointCloud.size() > MAX_POINT_COUNT) {
                            pointCloud.remove(0);
                        }
                    }
                } catch (Exception e) {
                    log.error("Failed to parse point cloud data. Raw data: {}. Error: {}", validJson, e);
                }
                // 从缓冲区中移除已处理的数据
                buffer.delete(0, endIndex + 1);
            } else {
                log.debug("No complete JSON array found in buffer, waiting for more data.");
                break;
            }
        }
    }

    public List<LidarPoint> getPointCloud() {
        return new ArrayList<>(pointCloud);
    }

    public void clearPoints() {
        pointCloud.clear();
    }

    public int getMaxPointCount() {
        return MAX_POINT_COUNT;
    }

    private void startPrintTask() {
        dataPrintTimer = new Timer();
        dataPrintTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                synchronized (pointCloud) {
                    if (!pointCloud.isEmpty()) {
                        log.info("Printing point cloud data: {}", pointCloud);
                    }
                }
            }
        }, 0, 5 * 1000);
    }
}
